package sqls

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/gorms"
	"github.com/mitchellh/mapstructure"
	"gorm.io/gorm"
)

type PageParam struct {
	ListSql     *RawSql
	CountSql    *RawSql
	M           map[string]interface{}
	CurrentPage int
	PageSize    int
}

// 列表查询
func List(ctx context.Context, db *gorm.DB, rawSql *RawSql, m map[string]interface{}, rs interface{}) error {
	sql, err := ExecuteSqlTemplate(ctx, rawSql, m)
	if err != nil {
		return err
	}
	resultMap := make([]map[string]interface{}, 0)
	err = db.Raw(sql, m).Find(&resultMap).Error
	if err != nil {
		return err
	}
	err = mapstructure.Decode(&resultMap, rs)
	if err != nil {
		return err
	}
	return nil
}

// 数量查询
func Count(ctx context.Context, db *gorm.DB, rawSql *RawSql, m map[string]interface{}, c *int) error {
	sql, err := ExecuteSqlTemplate(ctx, rawSql, m)
	if err != nil {
		return err
	}
	err = db.Raw(sql, m).Find(c).Error
	if err != nil {
		return err
	}
	return nil
}

// 分页查询
func Page(ctx context.Context, db *gorm.DB, pageParam PageParam, c *int, rs interface{}) error {
	err := Count(ctx, db, pageParam.CountSql, pageParam.M, c)
	if err != nil {
		return err
	}
	limit, offset := gorms.GetPage(pageParam.CurrentPage, pageParam.PageSize)
	pageParam.M["limit"] = limit
	pageParam.M["offset"] = offset
	err = List(ctx, db, pageParam.ListSql, pageParam.M, rs)
	if err != nil {
		return err
	}
	return nil
}
